﻿using jvm.instructions.common;
using jvm.rtda;
using jvm.rtda.heap;
using jvm.rtda.heap.clazz;
using jvm.rtda.heap.clazz.cp;
using jvm.rtda.heap.clazz.method;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace jvm.instructions.references
{
    class INVOKE_SPECIAL : Index16Instruction
    {
        public override void Execute(JFrame frame)
        {
            JClass curClass = frame.method.jClass;
            JConstantPool pool = curClass.constantPool;
            MethodRef methodRef = pool.GetConstant<MethodRef>(index);
            JClass methodClass = methodRef.ResolvedClass();
            JMethod method = methodRef.ResolvedMethod();
            if (method.name.Equals("<init>") && method.jClass != methodClass)
            {
                // 构造函数只在本类中声明，不能是父类或者接口中的
                Console.WriteLine("java.lang.NoSuchMethodError");
                Environment.Exit(0);
            }
            if (method.Is(AccessFlags.ACC_STATIC))
            {
                Console.WriteLine("java.lang.InCompatibleClassChangeError");
                Environment.Exit(0);
            }

            JObject thisObj = frame.operandStack.GetRefFromTop(method.argCount - 1);
            if (thisObj == null)
            {
                Console.WriteLine("java.lang.NullPointerException");
                Environment.Exit(0);
            }

            if (method.Is(AccessFlags.ACC_PROTECTED) &&
                method.jClass.IsSuperClassOf(curClass) &&
                method.jClass.PackageName() != curClass.PackageName() &&
                thisObj.jClass != curClass &&
                !thisObj.jClass.IsSubClassOf(curClass))
            {

                Console.WriteLine("java.lang.IllegalAccessError");
                Environment.Exit(0);
            }

            // 就是想调用super中的方法
            JMethod methodToBeInvoked = method;
            if (curClass.Is(AccessFlags.ACC_SUPER) &&
                methodClass.IsSuperClassOf(curClass) &&
                !method.name.Equals("<init>"))
            {
                methodToBeInvoked = MethodLookUp.LookUpMethodInClass(curClass.superClass, methodRef.name, methodRef.descriptor);
            }

            if (methodToBeInvoked == null || methodToBeInvoked.Is(AccessFlags.ACC_ABSTRACT))
            {
                Console.WriteLine("java.lang.AbstractMethodError");
                Environment.Exit(0);
            }
            InvokeUtil.InvokeMethod(frame, methodToBeInvoked);
        }
    }
}
